package itsm.isperp.module.controller.wechat.mp;

import itsm.isperp.framework.web.response.ResultMessage;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpGroup;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 微信用户组管理
 * 
 * 
 * @author lizx
 * @date 2014-11-4
 * @since 1.0
 * 
 */
@Controller
@RequestMapping("wechat/mp/group")
public class WechatMpGroupController {

	@Autowired
	WxMpService wxMpService;

	@RequestMapping(value = { "", "manage" })
	public ModelAndView manage(HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("wechat/mp/group/manage");
		return mv;
	}

	@RequestMapping("list")
	@ResponseBody
	public List<WxMpGroup> list() throws WxErrorException {
		return wxMpService.groupGet();
	}

	@RequestMapping("edit")
	public ModelAndView edit(String id, String name, HttpServletRequest req) {

		ModelAndView mv = new ModelAndView("wechat/mp/group/edit");

		mv.addObject("id", id);
		mv.addObject("name", name);
		return mv;
	}

	@RequestMapping("save")
	@ResponseBody
	public ResultMessage save(String id, String name, HttpServletRequest req)
			throws WxErrorException {

		if (StringUtils.isEmpty(id)) {

			wxMpService.groupCreate(name);
		} else {
			WxMpGroup group = new WxMpGroup();
			group.setName(name);
			group.setId(Long.valueOf(id));

			wxMpService.groupUpdate(group);
		}

		return ResultMessage.success();
	}
}
